from rest_framework.views import APIView
from . import models
from basics import models as basics_models
from . import serializers
from utils.get_query_params import GetQueryParams
from utils.commonviews import CommonAPIView
from rest_framework.response import Response
from utils.base_response import BaseResponse
from ProjectTool.WebTool.ParsingStepsWebData import ParsingStepsWebData


# Create your views here.


# 对应页面
class ModulePageModelViewSet(CommonAPIView):
    query_set = models.ModulePage.objects.all().order_by('id')
    serializer_class = serializers.ModulePageSerializers
    input_get_list = [
        ('module_page_id', 'id'),
        ('module_page_module_id', 'module'),
        ('module_page_project_id', 'project'),
        ('inputObjName', 'title__contains'),
        # ('inputObjName', 'title__contains'),
    ]
    input_put_list = [('module_page_id', 'id')]
    input_delete_list = [('module_page_id', 'id')]
    input_dict = GetQueryParams

    def post(self, request):
        res = BaseResponse()
        query_data = request.data
        module_obj = basics_models.Module.objects.filter(id=query_data.get('module')).first()
        module_project = module_obj.project.id
        if query_data.get('project') != module_project:
            res.status = 1
            res.msg = '项目与模块不匹配'
            return Response(res.dict)
        return self.create(request)

    def put(self, request):
        res = BaseResponse()
        query_data = request.data
        module_obj = basics_models.Module.objects.filter(id=query_data.get('module')).first()
        module_project = module_obj.project.id
        if query_data.get('project') != module_project:
            res.status = 1
            res.msg = '项目与模块不匹配'
            return Response(res.dict)
        return self.update(request)


# 标签定位表
class LabelElementModelViewSet(CommonAPIView):
    query_set = models.LabelElement.objects.all().order_by('id')
    serializer_class = serializers.LabelElementSerializers
    input_get_list = [('label_element_id', 'id'),
                      ('label_element_in_id', 'id__in'),
                      ('module_page_id', 'module_page'),
                      ('inputObjName', 'title__contains')]
    input_put_list = [('label_element_id', 'id')]
    input_delete_list = [('label_element_id', 'id')]
    input_dict = GetQueryParams

    def post(self, request):
        res = BaseResponse()
        query_data = request.data
        module_page_obj = models.ModulePage.objects.filter(id=query_data.get('module_page')).first()
        project = module_page_obj.project.id
        module = module_page_obj.module.id
        if query_data.get('project') != str(project):
            res.data = {'query_data_project': query_data.get('project'), 'project': project}
            res.status = 1
            res.msg = '项目与关联页面的项目不匹配'
            return Response(res.dict)
        elif str(query_data.get('module')) != str(module):
            res.status = 1
            res.msg = '模块与关联页面的模块不匹配'
            return Response(res.dict)
        return self.create(request)

    def put(self, request):
        res = BaseResponse()
        query_data = request.data
        module_page_obj = models.ModulePage.objects.filter(id=query_data.get('module_page')).first()
        project = module_page_obj.project.id
        module = module_page_obj.module.id
        if str(query_data.get('project')) != str(project):
            res.data = {'query_data_project': query_data.get('project'), 'project': project}
            res.status = 1
            res.msg = '项目与关联页面的项目不匹配'
            return Response(res.dict)
        elif str(query_data.get('module')) != str(module):
            res.status = 1
            res.msg = '模块与关联页面的模块不匹配'
            return Response(res.dict)
        return self.update(request)


# 执行函数
class SeleniumFuncModelViewSet(CommonAPIView):
    query_set = models.SeleniumFunc.objects.all().order_by('id')
    serializer_class = serializers.SeleniumFuncSerializers
    input_get_list = [
        ('selenium_func_id', 'id'),
        ('module_page_id', 'module_page'),
        ('inputObjName', 'title__contains'),
    ]
    input_put_list = [('selenium_func_id', 'id')]
    input_delete_list = [('selenium_func_id', 'id')]
    input_dict = GetQueryParams

    def post(self, request):
        res = BaseResponse()
        query_data = request.data
        module_page_obj = models.ModulePage.objects.filter(id=query_data.get('module_page')).first()
        project = module_page_obj.project.id
        module = module_page_obj.module.id
        label_elements = module_page_obj.labelelement_set.filter(status=1).values('id', 'title')
        if str(query_data.get('project')) != str(project):
            res.data = {'query_data_project': query_data.get('project'), 'project': project}
            res.status = 1
            res.msg = '项目与关联页面的项目不匹配'
            return Response(res.dict)
        elif str(query_data.get('module')) != str(module):
            res.status = 1
            res.msg = '模块与关联页面的模块不匹配'
            return Response(res.dict)
        not_keys = []
        for i in query_data.get('label_element'):
            stas = False
            for lis in label_elements:
                if i == lis.get('id'):
                    stas = True
            if not stas:
                not_keys.append(i)
        if not_keys:
            obj = list(models.LabelElement.objects.filter(id__in=not_keys).values('id', 'title'))
            res.data = {'label_elements': label_elements, 'not_label_elements': obj}
            res.status = 1
            res.msg = '存在与页面不相关的元素：{obj}'.format(obj=obj)
            return Response(res.dict)
        return self.create(request)

    def put(self, request):
        res = BaseResponse()
        query_data = request.data
        module_page_obj = models.ModulePage.objects.filter(id=query_data.get('module_page')).first()
        project = module_page_obj.project.id
        module = module_page_obj.module.id
        label_elements = module_page_obj.labelelement_set.filter(status=1).values('id', 'title')
        if str(query_data.get('project')) != str(project):
            res.data = {'query_data_project': query_data.get('project'), 'project': project}
            res.status = 1
            res.msg = '项目与关联页面的项目不匹配'
            return Response(res.dict)
        elif str(query_data.get('module')) != str(module):
            res.status = 1
            res.msg = '模块与关联页面的模块不匹配'
            return Response(res.dict)
        not_keys = []
        for i in query_data.get('label_element'):
            stas = False
            for lis in label_elements:
                if i == lis.get('id'):
                    stas = True
            if not stas:
                not_keys.append(i)
        if not_keys:
            obj = list(models.LabelElement.objects.filter(id__in=not_keys).values('id', 'title'))
            res.data = {'label_elements': label_elements, 'not_label_elements': obj}
            res.status = 1
            res.msg = '存在与页面不相关的元素：{obj}'.format(obj=obj)
            return Response(res.dict)
        return self.update(request)


# 步骤表
class StepsModelViewSet(CommonAPIView):
    query_set = models.Steps.objects.all().order_by('id')
    serializer_class = serializers.StepsSerializers
    input_get_list = [
        ('steps_id', 'id'),
        ('project_id', 'project'),
        ('module_id', 'module'),
        ('obj_key', 'obj_key'),
        ('results', 'results'),
        ('status', 'status'),
        ('inputObjName', 'title__contains'),
    ]
    input_put_list = [('steps_id', 'id')]
    input_delete_list = [('steps_id', 'id')]
    input_dict = GetQueryParams

    def post(self, request):
        res = BaseResponse()
        query_data = request.data
        module_obj = basics_models.Module.objects.filter(id=query_data.get('module')).first()
        module_project = module_obj.project.id
        if query_data.get('project') != module_project:
            res.status = 1
            res.msg = '项目与模块不匹配'
            return Response(res.dict)
        return self.create(request)

    def put(self, request):
        res = BaseResponse()
        query_data = request.data
        module_obj = basics_models.Module.objects.filter(id=query_data.get('module')).first()
        module_project = module_obj.project.id
        if query_data.get('project') != module_project:
            res.status = 1
            res.msg = '项目与模块不匹配'
            return Response(res.dict)
        return self.update(request)


# 测试步骤
class TestSteps(APIView):
    def get(self, request):
        res = BaseResponse()
        # 查询数据库中的数据
        steps_id = request.GET.get('id')
        try:
            obj = ParsingStepsWebData(steps_id=steps_id)
            res = obj.run()
            if obj.driver:
                obj.driver.quit()
            return Response(res)
        except Exception as e:
            res.status = 1
            res.msg = '执行失败'
            res.error = str(e.args)
            raise e
        return Response(res.dict)


# 步骤实现表
class StepsRealizeModelViewSet(CommonAPIView):
    query_set = models.StepsRealize.objects.all().order_by('steps', 'sort')
    serializer_class = serializers.StepsRealizeSerializers
    input_get_list = [
        ('steps_realize_id', 'id'),
        ('project_id', 'project'),
        ('module_id', 'module'),
        ('steps_id', 'steps'),
        ('module_page_id', 'module_page'),
        ('selenium_func_id', 'selenium_func'),
        ('inputObjName', 'title__contains'),
        ('results', 'results'),
        ('status', 'status'),
        ('obj_key', 'obj_key'),
    ]
    input_put_list = [('steps_realize_id', 'id')]
    input_delete_list = [('steps_realize_id', 'id')]
    input_dict = GetQueryParams

    def post(self, request):
        res = BaseResponse()
        query_data = request.data
        project_obj = basics_models.Project.objects.filter(id=query_data.get('project'), status=1)
        if not project_obj.count():
            res.status = 1
            res.msg = '项目不存在'
            return Response(res.dict)
        project_obj = project_obj.first()
        module_obj = project_obj.module_set.filter(id=query_data.get('module'), status=1)
        if not module_obj.count():
            res.status = 1
            res.msg = '项目与模块不匹配'
            return Response(res.dict)
        module_obj = module_obj.first()
        module_page_obj = module_obj.modulepage_set.filter(id=query_data.get('module_page'), status=1)
        if not module_page_obj.count():
            res.status = 1
            res.msg = '模块与页面不匹配'
            return Response(res.dict)
        module_page_obj = module_page_obj.first()
        selenium_func_obj = module_page_obj.seleniumfunc_set.filter(id=query_data.get('selenium_func'), status=1)
        if not selenium_func_obj.count():
            res.status = 1
            res.msg = '页面与函数不匹配'
            return Response(res.dict)
        return self.create(request)

    def put(self, request):
        res = BaseResponse()
        query_data = request.data
        project_obj = basics_models.Project.objects.filter(id=query_data.get('project'), status=1)
        if not project_obj.count():
            res.status = 1
            res.msg = '项目不存在'
            return Response(res.dict)
        project_obj = project_obj.first()
        module_obj = project_obj.module_set.filter(id=query_data.get('module'), status=1)
        if not module_obj.count():
            res.status = 1
            res.msg = '项目与模块不匹配'
            return Response(res.dict)
        module_obj = module_obj.first()
        module_page_obj = module_obj.modulepage_set.filter(id=query_data.get('module_page'), status=1)
        if not module_page_obj.count():
            res.status = 1
            res.msg = '模块与页面不匹配'
            return Response(res.dict)
        module_page_obj = module_page_obj.first()
        selenium_func_obj = module_page_obj.seleniumfunc_set.filter(id=query_data.get('selenium_func'), status=1)
        if not selenium_func_obj.count():
            res.status = 1
            res.msg = '页面与函数不匹配'
            return Response(res.dict)
        return self.update(request)


# 测试步骤提升
class StepsRealizeAscension(APIView):
    def get(self, request):
        res = BaseResponse()
        # 查询数据库中的数据
        steps_realize_id = request.GET.get('id')
        obj = models.StepsRealize.objects.filter(id=steps_realize_id).first()
        query_set = models.StepsRealize.objects.filter(steps=obj.steps).order_by('sort')
        now_obj = query_set.filter(id=steps_realize_id).first()
        now_sort = now_obj.sort  # 当前
        on_sort = now_sort - 1  # 上一步
        excessive_sort = query_set[len(query_set) - 1].sort + 1 if len(query_set) else None  # 过度步骤
        if on_sort > 0:
            on_obj = query_set.filter(sort=on_sort)
            if on_obj.count():
                on_obj = on_obj.first()
                on_obj.sort = excessive_sort
                on_obj.save()
                now_obj.sort = on_sort
                now_obj.save()
                on_obj.sort = now_sort
                on_obj.save()
            else:
                now_obj.sort = on_sort
                now_obj.save()
        return Response(res.dict)
